package pl.edu.pw.perg.compinfodb.datamodel;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

public class SearchTableModel implements TableModel {

	private FlexibleTableColumnModel ftcm = new FlexibleTableColumnModel(new DefaultTableCellRenderer());
	private Map<String, String> filters = new HashMap<String, String>();
	private List<TableModelListener> listeners = new ArrayList<TableModelListener>();
	private DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
	private List<ISearchFilterListener> searchFilterListeners = new ArrayList<ISearchFilterListener>();
	
	public int getRowCount() {
		return 1;
	}
	
	public void setColumnModel(FlexibleTableColumnModel tcm){
		ftcm = tcm;
//		ftcm.setColumnNames(tcm.getColumnNames());
//		Enumeration<TableColumn> tcs = tcm.getColumns();
//		while(tcs.hasMoreElements()){
//			int width = tcs.nextElement().getWidth();
//			ftcm.getColumns().nextElement().setWidth(width);
//		}
//		ftcm.setRenderer(renderer);
		for (TableModelListener tml : listeners) {
			((JTable) tml).setColumnModel(ftcm);
		}
		filters.clear();
//		refreshRenderer();
	}

	public void addTableModelListener(TableModelListener l) {
		listeners.add(l);
		
	}
	
	public void addSearchFilterListener(ISearchFilterListener l) {
		searchFilterListeners.add(l);
		
	}

	public Class<?> getColumnClass(int columnIndex) {
		return String.class;
	}

	public int getColumnCount() {
		return ftcm.getColumnCount();
	}

	public String getColumnName(int columnIndex) {
		return ftcm.getColumn(columnIndex).getHeaderValue().toString();
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
//		if(columnIndex >= filters.size())
//			return "";
		return filters.get(ftcm.getColumnNames()[columnIndex]);
	}

	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return true;
	}

	public void removeTableModelListener(TableModelListener l) {
		listeners.remove(l);
		
	}

	public void setValueAt(Object value, int rowIndex, int columnIndex) {
		filters.put(ftcm.getColumnNames()[columnIndex], value.toString());
		filterChanged(filters);
	}
	
	public void filterChanged(Map<String, String> filter){
		for (ISearchFilterListener searchFilterListener : searchFilterListeners) {
			searchFilterListener.filterChanged(filter);
		}
	}
	
	
}
